$(document).ready(function() {
  $('form').on('submit', function(event) {
    event.preventDefault(); // 阻止表单的默认提交行为

    const username = $('.username').val();
    const password = $('.password').val();

    if (!username || !password) {
      $('.error').text('用户名或密码不能为空！').show();
      return;
    }

    $.ajax({
      url: 'http://localhost:9000/users/login',
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({ username, password }),
      success: function(response) {
        if (response.code === 1) {
          alert(response.message);
          // 存储token, id, 和 nickname到localStorage
          localStorage.setItem('token', response.token);
          localStorage.setItem('userId', response.user.id);
          localStorage.setItem('nickname', response.user.nickname);
          console.log(response.token); // 修正此行，输出response.token
          // 重定向到main.html
          window.location.href = 'main.html';
        } else {
          $('.error').text('用户名或密码错误！').show();
        }
      },
      error: function() {
        $('.error').text('服务器错误，请稍后再试！').show();
      }
    });
  });
});
